//
//  DDropIntoView.swift
//  Drop
//
//  Created by hushaohua on 2017/12/22.
//  Copyright © 2017年 init. All rights reserved.
//

import UIKit

class DIntoCollectionView : UICollectionView{
    
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        var endPoint:CGPoint = point;
        if (UIMenuController.shared.isMenuVisible){
            endPoint.x = self.bounds.width / 2;
        }
//        print("collectionview-hittest:\(endPoint.x),\(endPoint.y),\(UIMenuController.shared.isMenuVisible)")
        return super.hitTest(endPoint, with: event);
    }
}

class DDropIntoView: UIView {
    
    lazy var collectionView:UICollectionView = {
        let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout();
        layout.minimumLineSpacing = 20;
        layout.minimumInteritemSpacing = 20;
        layout.itemSize = CGSize(width:(self.bounds.width - 48 - 20) / 2,height:80);
        layout.sectionInset = UIEdgeInsetsMake(0, 24, 12, 24);
        var collectionView:UICollectionView = DIntoCollectionView(frame: CGRect(x:0,y:0,width:self.bounds.size.width,height:self.bounds.size.height), collectionViewLayout: layout);
        collectionView.keyboardDismissMode = .onDrag;
        collectionView.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin, .flexibleHeight];
        collectionView.backgroundColor = UIColor.clear;
        return collectionView;
    }();
    
    override init(frame: CGRect) {
        super.init(frame: frame);
        self.addSubview(self.collectionView);
        self.addSubview(self.fakeButton);
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var fakeButton:UIButton = {
        var button:UIButton = UIButton(frame: CGRect(x:0,y:20,width:self.bounds.width,height:44));
        button.setTitle("搜索", for: .normal);
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16);
        button.setTitleColor(UIColor(white:0.7, alpha:1), for: .normal);
        button.addTarget(self, action: #selector(fakeButtonClicked(_:)), for: .touchUpInside);
        return button;
    }();
    
    @objc func fakeButtonClicked(_ sender:UIButton) -> Void{
        self.addSubview(self.textField);
        self.fakeButton.removeFromSuperview();
        self.textField.becomeFirstResponder();
    }
    
    lazy var textField:UITextField = {
        var field:UITextField = UITextField(frame: CGRect(x:0,y:20,width:self.bounds.width,height:44));
        field.attributedPlaceholder = NSAttributedString(string: "搜索", attributes:[.font : UIFont.systemFont(ofSize: 16), .foregroundColor : UIColor(white:0.7, alpha:1)]);
        field.textColor = UIColor.white;
        field.textAlignment = .center;
        field.returnKeyType = .search;
        return field;
    }();
    
    func layoutWithKeyboard(_ isKeyboard:Bool) -> Void {
        self.collectionView.reloadData();
    }
}
